package org.example.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.common.constant.Issuer;
import org.example.db.entity.User;
import org.example.db.entity.WxUser;
import org.example.db.mapper.UserMapper;
import org.example.db.mapper.WxUserMapper;
import org.example.security.exception.SecurityAuthException;
import org.example.security.util.JwtTokenUtil;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AuthService {

    UserMapper userMapper;
    PasswordEncoder passwordEncoder;
    JwtTokenUtil jwtTokenUtil;
    WxUserMapper wxUserMapper;

    public AuthService(UserMapper userMapper, PasswordEncoder passwordEncoder, JwtTokenUtil jwtTokenUtil, WxUserMapper wxUserMapper) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
        this.jwtTokenUtil = jwtTokenUtil;
        this.wxUserMapper = wxUserMapper;
    }

    public String login(String username, String password){

        List<User> userList = userMapper.selectList(new QueryWrapper<User>().lambda()
                .select(User::getId, User::getUsername, User::getPassword).eq(User::getUsername, username));

        if(userList.size() == 0){

            throw new SecurityAuthException("用户名或密码错误");
        }



        if(passwordEncoder.matches(password, userList.get(0).getPassword())){

            return jwtTokenUtil.generateToken(username, Issuer.fromAdmin);
        }else {
            throw new SecurityAuthException("用户名或密码错误");
        }
    }

    public String register(){

        // TODO
        return null;
    }

    public Long getUserId(){

        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // TODO 使用缓存

        return userMapper.selectList(
                new QueryWrapper<User>().lambda().eq(User::getUsername, userDetails.getUsername())).get(0).getId();
    }

    public Long getWxUserId(){

        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // TODO 使用缓存

        return wxUserMapper.selectList(
                new QueryWrapper<WxUser>().lambda().eq(WxUser::getId, userDetails.getUsername())).get(0).getId();
    }
}
